/**
 * 
 */
package com.desksoft.ecommerce.handler.controller.logistics;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.bind.ServletRequestDataBinder;

import com.desksoft.ecommerce.handler.controller.ControllerBase;
import com.desksoft.utility.query.QueryVO;

/***************************************
 * <pre>
 * 版权所有：杭州迪科软件 保留所有权利
 * 创建日期: Oct 9, 2011 4:49:10 PM
 * 创建作者：yejw
 * 文件名称：LogisticsControllerBase.java
 * 版本：1.0
 * 功能：
 * 最后修改时间：Oct 9, 2011 4:49:10 PM
 * 修改记录：
 * </pre>
 *****************************************/
public class LogisticsControllerBase extends ControllerBase {
	
	/**
	 * 解析查询QueryVO
	 * @param		request			request对象
	 * 				voClass			queryVO对象的Class
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws IOException 
	 */
	public QueryVO parseQueryVO(HttpServletRequest request,Class<?> voClass) throws InstantiationException, IllegalAccessException, IOException{
		QueryVO queryVO = (QueryVO) voClass.newInstance();
		
		String filter = request.getParameter("filters");
		
		if (filter!=null){
			queryVO = this.parseAdvancedQueryVO(request, queryVO);
		}else{
			queryVO = this.parseSimpleQueryVO(request, queryVO);
		}
		
		return queryVO;
	}
	
	/**
	 * 解析高级QueryVO
	 * ----		对象属性为空，值全在items属性中
	 * @throws IOException 
	 */
	protected QueryVO parseAdvancedQueryVO(final HttpServletRequest request,final QueryVO queryVO) throws IOException{
		
		final String filter = request.getParameter("filters");
		if (filter == null || "".equals(filter)){
			queryVO.setAdvanced(false);
		}else{
			queryVO.setAdvanced(true);
		}
		
		HttpInputMessage inputMessage = new HttpInputMessage(){
			@Override
			public HttpHeaders getHeaders() {
				return new HttpHeaders();
			}
			@Override
			public InputStream getBody() throws IOException {
				if (filter == null || "".equals(filter)){
					queryVO.setAdvanced(false);
					return new ByteArrayInputStream("{}".getBytes("UTF-8"));
				}else{
					queryVO.setAdvanced(true);
					return new ByteArrayInputStream(filter.getBytes("UTF-8"));
				}
			}
		};
		
		if (queryVO.isAdvanced()){
			MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter();
			QueryVO qvo = (QueryVO) jsonConverter.read(queryVO.getClass(), inputMessage);
			qvo.setAdvanced(true);
			return qvo;
		}else{
			return queryVO;
		}

	}
	
	/**
	 * 解析普通QueryVO
	 * ----		items属性为空，值全在对象属性中
	 */
	protected QueryVO parseSimpleQueryVO(HttpServletRequest request,QueryVO queryVO){
		ServletRequestDataBinder binder = new ServletRequestDataBinder(queryVO);
		binder.bind(request);
		return queryVO;
	}

}
